<template>
    <div>
      <h2>报名选课</h2>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/MemberMain">主页</el-breadcrumb-item>
        <el-breadcrumb-item>报名选课</el-breadcrumb-item>
      </el-breadcrumb>
  
      <el-card style="margin-top: 20px;">
        <el-table :data="tableData" style="width: 100%;" v-loading="loading">
          <el-table-column prop="classId" label="编号" />
          <el-table-column prop="className" label="名称" />
          <el-table-column prop="classBegin" label="时间" />
          <el-table-column prop="classTime" label="时长" />
          <el-table-column prop="coach" label="教练" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="primary" size="small" @click="onApply(scope.row)">报名</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            style="margin-top: 20px; text-align: center"
            background
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
        >
          <template #total>
            共 {{ total }} 条
          </template>
          <template #jumper>
            跳转到
            <el-input
                class="el-pagination__editor is-in-pagination"
                v-model.number="jumperPage"
                type="number"
                size="small"
                @keyup.enter.native="jumpToPage"
                :min="1"
                :max="Math.ceil(total / pageSize)"
            />
            页
          </template>
        </el-pagination>
      </el-card>

    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  
  const tableData = ref([])
  const loading = ref(false)

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const jumperPage = ref(null)

  //用户信息
  const LoginMemberAccount = ref('')
  const LoginMemberName = ref('')

  const loadData = () => {
    loading.value = true
    axios.get('/server/class/search', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
        .then(response => {
          if (response.data.code === 200) {
            tableData.value = response.data.data.records
            total.value = response.data.data.total
          } else {
            ElMessage.error('获取数据失败: ' + (response.data.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('获取课程数据失败:', error)
          ElMessage.error('加载课程数据失败')
        })
        .finally(() => {
          loading.value = false
        })
  }

  onMounted(() => {
    //检查是否登录
    if(!localStorage.getItem('token')){
      ElMessage.error('请先登录')
      router.push('/MemberLogin')
      return
    }
    getMemberInfo()
    loadData()
  })

  // 跳转到页
  const jumpToPage = () => {
    const maxPage = Math.ceil(total.value / pageSize.value)
    if (jumperPage.value >= 1 && jumperPage.value <= maxPage) {
      currentPage.value = jumperPage.value
      loadData()
    } else {
      ElMessage.warning('请输入有效页码')
    }
  }

  const getMemberInfo = () => {
    axios.get('/server/member/getMyInfo',{
      headers: {
        'Authorization': localStorage.getItem('token')
      }
    }).then(res => {
      if(res.data.code === 200){
        LoginMemberAccount.value = res.data.data.memberAccount
        LoginMemberName.value = res.data.data.memberName
      }else {
        ElMessage.error('无法获取用户名')
      }
    }).catch(() => {
      ElMessage.error('请求数百，无法获取用户名')
    })
  }

  const onApply = (row) => {
    // 获取当前用户信息（
    const memberAccount = LoginMemberAccount
    const memberName = LoginMemberName

    if (!memberAccount.value) {
      ElMessage.error('请先登录')
      return
    }

    axios.post('/server/classOrder/add',
        {
          classId: row.classId,
          className: row.className,
          coach: row.coach,
          classBegin: row.classBegin,
          memberAccount: LoginMemberAccount.value,
          memberName: LoginMemberName.value || '' // 可选字段
        },
        {
          headers: {
            'Authorization': localStorage.getItem('token')
          },
          withCredentials: true
        }
    )
        .then(response => {
          if (response.data.code === 200) {
            ElMessage.success('报名成功')
            loadData()
          } else {
            ElMessage.error('报名失败: ' + (response.data.message || '未知错误'))
          }
        })
        .catch(error => {
          console.error('报名请求失败:', error)
          ElMessage.error('请求失败，无法报名')
        })
  }

  </script>
  
  <style scoped>
  h2 {
    margin-bottom: 10px;
  }
  </style>
  